package com.itheima.controller;


import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookServlet {
    @Autowired
    private BookService bookService;

    @GetMapping
    public Result selectAll(){
        List<Book> books = bookService.selectAll();
        Integer code=books!=null?Code.GET_OK:Code.GET_ERR;
        String msg=books!=null?"":"未查到数据，请稍后重试";
        return new Result(code,books,msg);
    }

    @GetMapping("/{id}")
    public Result selectById(@PathVariable int id ){
        Book book = bookService.selectById(id);
        Integer code=book!=null?Code.GET_OK:Code.GET_ERR;
        String msg=book!=null?"":"未查到数据，请稍后重试";
        return new Result(code,book,msg);
    }

    @PostMapping
    public Result add(@RequestBody Book book){
        boolean flag = bookService.add(book);
        return new Result(flag?Code.ADD_OK:Code.ADD_ERR,flag);
    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable int id){
        boolean flag = bookService.deleteById(id);
        return new Result(flag?Code.DELETE_OK:Code.DELETE_ERR,flag);
    }

    @PutMapping
    public Result update(@RequestBody Book book){
        boolean flag = bookService.update(book);
        return new Result(flag?Code.UPDATE_OK:Code.UPDATE_ERR,flag);
    }
}
